
function loadLyric(audio,text){
	var result = null;
	var myaudio = audio;
	var path = text;
	
	$.ajax({
		url:path,
		type:'post',
		dataType:'text',
		success:function(data){
			result = parseLyric(data);
			appendLyric(result);
		},
		error:function(data){
			$("#lrcContainer").html("<p>加载歌词失败....</p>");
		}
	});
	
	myaudio.ontimeupdate = function(e){
		
		for(var i=0; i<result.length;i++){
			if(this.currentTime>result[i][0]){
				var line = $("#line-"+i)[0];
				$("#line-"+(i-1)).removeClass("dcw");
				$("#line-"+i).addClass("dcw");
				$("#line-"+(i+1)).remove("dcw");
				$("#lrcContainer").css("top",(130-line.offsetTop)+"px");
			}
		}
	};
}
function parseLyric(text){
	var lines = text.split("\n");
	var pattern = /\[\d{2}:\d{2}.\d{2}\]/g;
	var offset = getOffSet(text);
	var result = [];
	while (!pattern.test(lines[0])) {
           lines = lines.slice(1);
          }//去掉头
          lines[lines.length - 1].length === 0 && lines.pop();
            
          lines.forEach(function(v,i,a){
        	  	var time = v.match(pattern);
        	  	var value = v.replace(pattern,'');
           		
           		time.forEach(function(v1, i1, a1) {
                	//convert the [min:sec] to secs format then store into result
                	var t = v1.slice(1, -1).split(':');
                	result.push([parseInt(t[0], 10) * 60 + parseFloat(t[1]) + parseInt(offset) / 1000, value]);
            	});
           	});
           	result.sort(function(a, b) {
            	return a[0] - b[0];
        });
        	
        return result;
}

function getOffSet(text){
	var offset = 0;
    try {
        var offsetPattern = /\[offset:\-?\+?\d+\]/g,
            offset_line = text.match(offsetPattern)[0],
            offset_str = offset_line.split(':')[1];
          	offset = parseInt(offset_str);
        } catch (err) {
            offset = 0;
        }
        return offset;
}

function appendLyric(text){
	var html="";
	text.forEach(function(v,i,a){
			html+="<p id='line-"+i+"'>"+v[1]+"</p>";
	});
	$("#lrcContainer").html(html);
}